package com.example.xxcjgl.utils

import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec

//Encryption.kt
object EncryptionUtils {
    private const val ALGORITHM = "AES"
    private const val TRANSFORMATION = "AES/GCM/NoPadding"

    fun encrypt(data: String, key: String): String? {
        return try {
            val secretKey = generateKey(key)
            val cipher = Cipher.getInstance(TRANSFORMATION)
            cipher.init(Cipher.ENCRYPT_MODE, secretKey)
            val encryptedBytes = cipher.doFinal(data.toByteArray())
            Base64.encodeToString(encryptedBytes, Base64.DEFAULT)
        } catch (e: Exception) {
            null
        }
    }

    fun decrypt(encryptedData: String, key: String): String? {
        return try {
            val secretKey = generateKey(key)
            val cipher = Cipher.getInstance(TRANSFORMATION)
            cipher.init(Cipher.DECRYPT_MODE, secretKey)
            val encryptedBytes = Base64.decode(encryptedData, Base64.DEFAULT)
            val decryptedBytes = cipher.doFinal(encryptedBytes)
            String(decryptedBytes)
        } catch (e: Exception) {
            null
        }
    }

    private fun generateKey(key: String): SecretKey {
        val keyBytes = key.toByteArray()
        val sha = MessageDigest.getInstance("SHA-256")
        val digest = sha.digest(keyBytes)
        return SecretKeySpec(digest.copyOf(16), ALGORITHM) // 使用前16字节作为AES-128密钥
    }

    fun hashPassword(password: String): String {
        return try {
            val digest = MessageDigest.getInstance("SHA-1")
            val hashBytes = digest.digest(password.toByteArray())
            hashBytes.joinToString("") { "%02x".format(it) }
        } catch (e: Exception) {
            password // 失败时返回原密码
        }
    }

    fun generateRandomKey(length: Int = 16): String {
        val chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
        return (1..length).map { chars.random() }.joinToString("")
    }

    fun isStrongKey(key: String): Boolean {
        return key.length >= 8 &&
                key.any { it.isUpperCase() } &&
                key.any { it.isLowerCase() } &&
                key.any { it.isDigit() }
    }
}